package com.example.monitoringsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.monitoringsystem.bean.Doctor;
import com.example.monitoringsystem.bean.DoctorWorkTime;
import com.example.monitoringsystem.mapper.DoctorMapper;
import com.example.monitoringsystem.mapper.DoctorWorkTimeMapper;
import com.example.monitoringsystem.service.DoctorWorkTimeService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;


@Service
public class DoctorWorkTimeServiceImpl implements DoctorWorkTimeService {
    @Autowired
    private DoctorWorkTimeMapper doctorWorkTimeMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public String getWorkTimeByDoctorId(Integer doctorId) {
        QueryWrapper<DoctorWorkTime> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("doctor_id",doctorId);
        DoctorWorkTime doctorWorkTime = doctorWorkTimeMapper.selectOne(queryWrapper);
        // 当医生刚注册时的工作时间为空，向数据库中添加一行。
        if (Objects.isNull(doctorWorkTime)){
            doctorWorkTime = new DoctorWorkTime(doctorId, Strings.repeat("0",336));
            doctorWorkTimeMapper.insert(doctorWorkTime);
        }
        return doctorWorkTime.getWorkTime();
    }

    @Override
    public void updateWorkTimeByDoctorId(DoctorWorkTime doctorWorkTime) {
        UpdateWrapper<DoctorWorkTime> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("doctor_id",doctorWorkTime.getDoctorId());
        doctorWorkTimeMapper.update(doctorWorkTime,updateWrapper);
    }

    @Override
    public List<DoctorWorkTime> getAllDoctorWorkTime(){
        List<DoctorWorkTime> doctorWorkTimes = doctorWorkTimeMapper.selectList(null);
        List<Doctor> doctors = doctorMapper.selectList(null);
        // 当有一些刚注册的医生时,则初始化这些医生的工作时间为0
        if (doctors.size() > doctorWorkTimes.size()){
            doctorWorkTimes.sort(new Comparator<DoctorWorkTime>() {
                @Override
                public int compare(DoctorWorkTime o1, DoctorWorkTime o2) {
                    return o1.getDoctorId().compareTo(o2.getDoctorId());
                }
            });
            doctors.sort(new Comparator<Doctor>() {
                @Override
                public int compare(Doctor o1, Doctor o2) {
                    return o1.getDoctorId().compareTo(o1.getDoctorId());
                }
            });
            int i;
            for(Doctor doctor : doctors){
                getWorkTimeByDoctorId(doctor.getDoctorId());
            }
            doctorWorkTimes = doctorWorkTimeMapper.selectList(null);
        }
        return doctorWorkTimes;
    }
}
